package controllers;

import helpers.CrawlerHelper;
import helpers.FileHelper;
import helpers.IpHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.RecentlyDomain;

import debugs.DomainDebug;

import entities.Domain;

public class DomainServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(DomainServlet.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {

		TreeMap<String, String> check = new TreeMap<String, String>();
        Domain domain = new Domain();
        
        String path = ((HttpServletRequest) request).getRequestURI();
        String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
        
        domain.setDomain(name);
        //Convert to main domain
        if (name != null && !name.isEmpty()) {
                name = UrlHelper.getMainDomain(name);
                if (!UrlHelper.checkDomain(name)) {
                        check.put("name", name + " is not a domain. Please enter again!");
                }
                
                if (check.size() == 0) {
                	
                    //Check domain exists db
                    domain = FileHelper.getByFileName(name);
                    DomainDebug.debug(domain);
                    if (domain == null) {
                        domain = new Domain();
                        domain.setDomain(name);
                        
                        domain = CrawlerHelper.getDns(domain);
                        DomainDebug.debug(domain);
                        if (domain != null) {
                            FileHelper.saveToObject(domain);
                            log.info("Update success new domain: " + name);
                        } else {
                            log.warning("Not exists domain: " + name);
                        }
                    } else {
                        log.info("Get domain " + name + " from database");
                    }
                    
                    RecentlyDomain.insert(name);
                }
        } else {
                response.sendRedirect("/");
                return;
        }
        
        request.setAttribute("name", name);
        request.setAttribute("domain", domain);
        request.setAttribute("check", check);
        try {
			request.getRequestDispatcher("/pages/dns.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
			/*response.sendRedirect("/");
			return;*/
		}
	}
}
